//
//  SPFriendListController.m
//  Sport
//
//  Created by _LJX on 2018/5/9.
//  Copyright © 2018年 Cass. All rights reserved.
//

#import "SPFriendListController.h"
#import "SPContract.h"
#import "SPConversationViewController.h"
#import "SPContractCell.h"
@interface SPFriendListController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *friendsList;

@end

@implementation SPFriendListController


-(NSArray *)friendsList{
    if (_friendsList == nil) {
        
        NSArray *phoneList = [NSArray arrayWithObjects:@"17780682480",@"18328700795",@"13629049722",@"17602853684",@"17602882307",@"18328067022",@"15520446187",@"13980542220",@"18780171298",@"13208115595", nil];
        
        NSMutableArray *muArr = [[NSMutableArray alloc]init];
        for (NSString *phone in phoneList) {
            __block NSDictionary *contract;
            __block NSError *Error;
            NSURLSession *session = [NSURLSession sharedSession];
            NSURL *url = [NSURL URLWithString:@"http://39.108.132.194/Sport/returnUserPicAndNick.php"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            request.HTTPMethod = @"POST";
            request.HTTPBody = [[NSString stringWithFormat:@"phoneNum=%@",phone] dataUsingEncoding:NSUTF8StringEncoding];
            NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                if (!error) {
                    NSArray *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
                    NSDictionary *arr = dict.firstObject;
                    contract = arr;
                }else{
                    NSLog(@"失败");
                    Error = error;
                }
            }];
            [dataTask resume];
            while (!contract&&!Error) {}
            NSDictionary *information = [NSDictionary dictionaryWithObjectsAndKeys:phone,@"phone",
                                                                            [contract objectForKey:@"headimage"],@"headimage",
                                         [contract objectForKey:@"nickname"],@"nickname",nil];
            [muArr addObject:information];
         }
        _friendsList = muArr;
        [self.tableView reloadData];
    }
    return _friendsList;
}

-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [self friendsList];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight  = 60;
        self.tableView.tableFooterView = [[UIView alloc]init];  
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _friendsList.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cell_id  = @"cell_id";
    SPContractCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"SPContractCell" owner:self options:nil].firstObject;
    }
    NSDictionary *dict = _friendsList[indexPath.row];
    cell.nickname.text =[dict objectForKey:@"nickname"];
    [cell.headPortrati sd_setImageWithURL:[NSURL URLWithString:[dict objectForKey:@"headimage"]]];
    return  cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = _friendsList[indexPath.row];
    SPConversationViewController *conversationVC = [[SPConversationViewController alloc]initWithConversationChatter:[dict objectForKey:@"phone"] conversationType:EMConversationTypeChat];
    conversationVC.title = [dict objectForKey:@"nickname"];
    conversationVC.nickname =  [dict objectForKey:@"nickname"];
    conversationVC.iconUrl = [dict objectForKey:@"headimage"];
    [self.navigationController pushViewController:conversationVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"加载");
    [self tableView];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
